package com.framework.bdf4j.comm.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: QL
 * @date: 2021/2/2 10:46
 */
@Component
public class RedisUtils {

    private static final String LOGIN = "LOGIN: username: ";

    @Value("${login.retryNumber}")
    private String retryNumber;
    @Value("${login.lockTime}")
    private String lockTime;
    @Value("${login.validTime}")
    private String validTime;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void checkUser(String username) {
        String key = LOGIN + username;
        Boolean exit = redisTemplate.hasKey(key);
        if (exit && ("true".equals(redisTemplate.opsForValue().get(key)))) {
            // 判断账号是否已锁定.
            Long l = redisTemplate.getExpire(key);
            throw new BadCredentialsException("账户已锁定，请 " + l + " 秒后再登录");
        } else if (exit && retryNumber.equals(redisTemplate.opsForValue().get(key))) {
            // 锁账号.
            redisTemplate.opsForValue().set(key, "true");
            // 设置 10 分钟的锁定时间.
            redisTemplate.expire(key, Integer.parseInt(lockTime), TimeUnit.SECONDS);
            throw new BadCredentialsException("账户已锁定，请 " + lockTime + " 秒后再登录");
        }
    }

    public void setLoginRedis(String username) {
        String key = LOGIN + username;
        if (redisTemplate.hasKey(key)) {
            if (!"true".equals(redisTemplate.opsForValue().get(key))) {
                redisTemplate.opsForValue().increment(key, 1);
            }
        } else {
            redisTemplate.opsForValue().set(key, "1", Integer.parseInt(validTime), TimeUnit.SECONDS);
        }
    }

    public void deleteRedis(String username) {
        String key = LOGIN + username;
        redisTemplate.delete(key);
    }

    public Integer getValue(String username) {
        String key = LOGIN + username;
        if (!"true".equals(redisTemplate.opsForValue().get(key))) {
            return Integer.parseInt(redisTemplate.opsForValue().get(key).toString());
        }
        return 0;
    }
}